package com.ctsi.ssdc.admin.web;

import java.net.URI;
import java.net.URISyntaxException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ctsi.ssdc.admin.domain.CscpMenus;
import com.ctsi.ssdc.model.AjaxBackData;

import com.zdww.biyi.component.sdk.aop.BeanExposeMethodAble;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ctsi.ssdc.admin.domain.dto.CscpMenusCriteria;
import com.ctsi.ssdc.admin.domain.dto.CscpMenusDTO;
import com.ctsi.ssdc.admin.service.CscpMenusService;
import com.ctsi.ssdc.annotation.Validate;
import com.ctsi.ssdc.exception.BadRequestAlertException;
import com.ctsi.ssdc.model.AjaxForm;
import com.ctsi.ssdc.model.MenuItemBean;
import com.ctsi.ssdc.model.PageResult;
import com.ctsi.ssdc.security.SecurityUtils;
import com.ctsi.ssdc.util.HeaderUtil;
import com.ctsi.ssdc.util.ResponseUtil;

import static com.ctsi.ssdc.admin.consts.ComponentConstant.ADMIN;
import static com.ctsi.ssdc.admin.consts.ComponentConstant.METHOD;


/**
 * REST controller for managing CscpMenus.
 *
 * @author ctsi biyi generator
 *
 */
@RestController
@RequestMapping("/api/system")
@Component
public class CscpMenusController {

    private final Logger log = LoggerFactory.getLogger(CscpMenusController.class);

    private static final String ENTITY_NAME = "cscpMenus";

    private final CscpMenusService cscpMenusService;

    public CscpMenusController(CscpMenusService cscpMenusService) {
        this.cscpMenusService = cscpMenusService;
    }

    @InitBinder   
    public void initBinder(WebDataBinder binder) {   
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");   
        dateFormat.setLenient(true);   
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   
    } 
    
    /**
     * POST  /cscpMenuss : Create a new cscpMenus.
     * @param cscpMenusDTO the cscpMenusDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new cscpMenusDTO, or with status 400 (Bad Request) if the cscpMenus has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/cscpMenuss")
    @BeanExposeMethodAble(component = ADMIN,method = METHOD)
    public ResponseEntity<CscpMenusDTO> createCscpMenus(@RequestBody CscpMenusDTO cscpMenusDTO) throws URISyntaxException {
        log.debug("REST request to save CscpMenus : {}", cscpMenusDTO);
        if (cscpMenusDTO.getId() != null) {
            throw new BadRequestAlertException("A new cscpMenus cannot already have an ID", ENTITY_NAME, "idexists");
        }
        CscpMenusDTO result = cscpMenusService.insert(cscpMenusDTO);
        return ResponseEntity.created(new URI("/api/cscpMenuss/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /cscpMenuss : Updates an existing cscpMenus.
     *
     * @param cscpMenusDTO the cscpMenusDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated cscpMenusDTO,
     * or with status 400 (Bad Request) if the cscpMenusDTO is not valid,
     * or with status 500 (Internal Server Error) if the cscpMenusDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/cscpMenuss")
    @BeanExposeMethodAble(component = ADMIN,method = METHOD)
    public ResponseEntity<CscpMenusDTO> updateCscpMenus(@RequestBody CscpMenusDTO cscpMenusDTO) throws URISyntaxException {
        log.debug("REST request to update CscpMenus : {}", cscpMenusDTO);
        if (cscpMenusDTO.getId() == null) {
            return createCscpMenus(cscpMenusDTO);
        }
        CscpMenusDTO result = cscpMenusService.update(cscpMenusDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, cscpMenusDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /cscpMenuss : get the cscpMenuss.
     *
     * @return the ResponseEntity with status 200 (OK) and the list of cscpMenuss in body
     */
    @GetMapping("/cscpMenuss")
    @BeanExposeMethodAble(component = ADMIN,method = METHOD)
    public PageResult<CscpMenusDTO> getCscpMenuss(CscpMenusDTO cscpMenusDTO, Pageable page) {
        log.debug("REST request to get CscpMenuss");
        return cscpMenusService.findByCscpMenusDTO(cscpMenusDTO, page);
    }
    
    /**
     * GET  /cscpMenuss : get the cscpMenuss.
     *
     * @return the ResponseEntity with status 200 (OK) and the list of cscpMenuss in body
     */
    @GetMapping("/cscpMenussByCriteria")
    @BeanExposeMethodAble(component = ADMIN,method = METHOD)
    public PageResult<CscpMenusDTO> getCscpMenussByCriteria(CscpMenusCriteria cscpMenusCriteria, Pageable page) {
        log.debug("REST request to get CscpMenussByCriteria");
        return cscpMenusService.findByCscpMenusCriteria(cscpMenusCriteria, page);
    }

    /**
     * GET  /cscpMenuss/:id : get the "id" cscpMenus.
     *
     * @param id the id of the cscpMenusDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the cscpMenusDTO, or with status 404 (Not Found)
     */
    @GetMapping("/cscpMenuss/{id}")
    @BeanExposeMethodAble(component = ADMIN,method = METHOD)
    public ResponseEntity<CscpMenusDTO> getCscpMenus(@PathVariable Integer id) {
        log.debug("REST request to get CscpMenus : {}", id);
        CscpMenusDTO cscpMenusDTO = cscpMenusService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(cscpMenusDTO));
    }
    /**
     * GET  /cscpMenuss/
     *
     * @return the ResponseEntity with status 200 (OK) and with body the cscpMenusDTO, or with status 404 (Not Found)
     */
    @GetMapping("/cscpMenus")
    @BeanExposeMethodAble(component = ADMIN,method = METHOD)
    public List<CscpMenusDTO> getCscpMenus() {
    	
    	int uid = SecurityUtils.getCurrentUserId();    	
        log.debug("REST request to get CscpMenus by userId: {}", uid);
        List<CscpMenusDTO> list = cscpMenusService.findByUserId(uid);
        return list;
    }

    /**
     * DELETE  /cscpMenuss/:id : delete the "id" cscpMenus.
     *
     * @param id the id of the cscpMenusDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/cscpMenuss/{id}")
    @BeanExposeMethodAble(component = ADMIN,method = METHOD)
    public ResponseEntity<Void> deleteCscpMenus(@PathVariable  Integer id) {
        log.debug("REST request to delete CscpMenus : {}", id);
        cscpMenusService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }
    
    @PostMapping(value="/menu/queryByRoleId")
    @BeanExposeMethodAble(component = ADMIN,method = METHOD)
	public ResponseEntity<MenuItemBean> roleMenuList(@RequestParam Integer roles){		
		
		MenuItemBean ls = cscpMenusService.roleMenuList(roles);
		return new ResponseEntity(ls, HttpStatus.OK);
	}
    
    @PostMapping(value="/menu/save")
	@Validate
    @BeanExposeMethodAble(component = ADMIN,method = METHOD)
	public ResponseEntity<AjaxForm> saveRoleMenus(@RequestParam Integer roles, @RequestParam String menus, @RequestParam String permissions){
    	cscpMenusService.saveRoleMenus(roles, menus, permissions);
		return new ResponseEntity(new AjaxForm(true, ""), HttpStatus.OK);
	}


    //自定义菜单增加与更新
    @PutMapping("/menu/addMenu")
    @BeanExposeMethodAble(component = ADMIN,method = METHOD)
    public AjaxBackData addMenu(@RequestBody CscpMenusDTO cscpMenusDto){
        AjaxBackData ajaxBackData = new AjaxBackData(true,"");
        if (cscpMenusDto != null){
            //判断权限是否存在 存在则更新，不存在则新增
            Integer id = cscpMenusDto.getId();
            if(cscpMenusService.findOne(id) != null){
                cscpMenusService.update(cscpMenusDto);
                log.debug("REST request to update CscpMenus : {}", id);
            }else{
                CscpMenusDTO newCscpMenusDto = cscpMenusService.insert(cscpMenusDto);
                log.debug("REST request to insert CscpMenus");
                //返回最新插入数据的id
                ajaxBackData.setId(newCscpMenusDto.getId().toString());
            }
        }
        return ajaxBackData;
    }

    //自定义菜单删除
    @DeleteMapping("/menu/deleteMenu/{id}")
    @BeanExposeMethodAble(component = ADMIN,method = METHOD)
    public AjaxBackData deleteMenu(@PathVariable Integer id){
        AjaxBackData ajaxBackData = new AjaxBackData();
        log.debug("REST request to delete CscpMenus : {}", id);
        if(id != null){
            cscpMenusService.delete(id);
        }
        return ajaxBackData;
    }
    //重写目录树get方法
    @GetMapping("/menu/getMenu")
    @BeanExposeMethodAble(component = ADMIN,method = METHOD)
    public PageResult<CscpMenus> getMenu(@RequestParam Integer parentId){
        log.debug("REST request to get all menus");
        //根据获取指定节点的孩子节点，若没有指定则找id=1的孩子节点
        List<CscpMenus> childs =new ArrayList();
        if(parentId == null){
            childs = cscpMenusService.findByParentId(1);
        }else{
            childs = cscpMenusService.findByParentId(parentId);
        }
        PageResult<CscpMenus> result = new PageResult<>();
        result.setData(childs);
        result.setRecordsTotal(childs.size());
        return result;
    }

      //异步路由树拖拽实现
      @PutMapping("/menu/updateMenu")
    public AjaxBackData updateOrderBy(@RequestBody CscpMenusDTO[] cscpMenusDtos){
        AjaxBackData ajaxBackData = new AjaxBackData(true,"");
        if (cscpMenusDtos.length <=0){
            return ajaxBackData;
        }else {
           for(CscpMenusDTO cscpMenusDto:cscpMenusDtos){
               if(cscpMenusDto.getOrderby()==0){
                    int orderBy =cscpMenusService.getOrderBy(cscpMenusDto);
                    cscpMenusDto.setOrderby(orderBy);
               }
               cscpMenusService.update(cscpMenusDto);
           }
        }
        return ajaxBackData;
    }

}
